package com.wfh.generator;

import cn.hutool.core.lang.Dict;
import cn.hutool.setting.yaml.YamlUtil;
import com.mybatisflex.codegen.Generator;
import com.mybatisflex.codegen.config.GlobalConfig;
import com.zaxxer.hikari.HikariDataSource;

import java.util.Map;

/**
 * @author fenghuanwang
 */
public class Codegen {

    // 要生成的表名称
    private static final String[] TBALE_NAMES = {"chat_history"};
    public static void main(String[] args) {
        // 获取数据源信息
        Dict dict = YamlUtil.loadByPath("application.yml");
        Map<Object, Object> datasourceConfig = dict.getByPath("spring.datasource");
        String url = (String) datasourceConfig.get("url");
        String password = (String) datasourceConfig.get("password");
        String username = (String) datasourceConfig.get("username");
        //配置数据源
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setJdbcUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);

        //创建配置内容，两种风格都可以。
        // GlobalConfig globalConfig = createGlobalConfigUseStyle1();
        GlobalConfig globalConfig = createGlobalConfig();

        //通过 datasource 和 globalConfig 创建代码生成器
        Generator generator = new Generator(dataSource, globalConfig);

        //生成代码
        generator.generate();
    }


    public static GlobalConfig createGlobalConfig() {
        //创建配置内容
        GlobalConfig globalConfig = new GlobalConfig();

        //设置根包
        globalConfig.getPackageConfig()
                .setBasePackage("com.wfh.aigenerator.gen");

        //设置表前缀和只生成哪些表，setGenerateTable 未配置时，生成所有表
        globalConfig.getStrategyConfig()
                .setGenerateTable(TBALE_NAMES)
                // 设置逻辑删除的字段名称
                .setLogicDeleteColumn("isDelete");

        //设置生成 entity 并启用 Lombok
        globalConfig.enableEntity()
                .setWithLombok(true)
                .setJdkVersion(21);

        //设置生成 mapper
        globalConfig.enableMapper();
        globalConfig.enableMapperXml();

        // 设置生成service
        globalConfig.enableService();
        globalConfig.enableServiceImpl();
        globalConfig.enableController();

       // 设置生成的注释
        globalConfig.getJavadocConfig().setAuthor("wangfenghuan")
                .setSince("");

        return globalConfig;
    }
}